﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Reflection;
using UMC.Wiki.Entities;
using UMC.Web;
using UMC.Web.UI;

namespace UMC.Wiki.Activities
{
    class SubjectTeamActivity : WebActivity
    {
        void Team(Project project)
        {
            var ui = UISection.Create();

            var pms = DataFactory.Instance().ProjectMember(project.Id.Value, WebAuthType.Admin, WebAuthType.User);
            var webr = UMC.Web.WebResource.Instance();
            var icons = new List<UIEventText>();
            var request = this.Context.Request;
            foreach (var id in pms)
            {

                icons.Add(new UIEventText(id.Alias).Src(webr.ImageResolve(request.Url, id.user_id.Value, "1", "4")).Click(UIClick.Pager(request.Model, "Account", new WebMeta().Put("Id", id.user_id), true)));  //: new UIClick(id.user_id.ToString()).Send(request.Model, "Account"));//);

                if (icons.Count % 4 == 0)
                {
                    ui.Add(new Web.UI.UIIcon().Add(icons.ToArray()));
                    icons.Clear();
                }

            }
            var style = new UIStyle().AlignLeft().Name("border", "none");
            if (icons.Count > 0)
            {
                var ls = new Web.UI.UIIcon().Add(icons.ToArray());
                ls.Style.Copy(style);
                ui.Add(ls);
            }
            this.Context.Response.Redirect(ui);
        }
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var productCode = this.AsyncDialog("Project", "auto");

            ulong teamId = UMC.Data.Utility.UInt64Parse(productCode) ?? 0;

            var project = teamId > 50000 ? DataFactory.Instance().Project(teamId) : DataFactory.Instance().Project(productCode);


            var user = this.Context.Token.Identity();
            var IsMaster = request.IsMaster;
            if (IsMaster == false)
            {
                var projectMember = DataFactory.Instance().ProjectMember(project.Id.Value, user.Id.Value);
                if (projectMember != null)
                {
                    switch (projectMember.AuthType)
                    {
                        case WebAuthType.Admin:
                            IsMaster = true;
                            break;
                    }
                }
            }
            var sId = this.AsyncDialog("Id", g =>
             {
                 if (String.Equals(this.AsyncDialog("Type", "PC"), "PC") == false)
                 {
                     Team(project);
                 }
                 var webr = UMC.Web.WebResource.Instance();
                 var form = request.SendValues ?? new UMC.Web.WebMeta();

                 int limit = UMC.Data.Utility.IntParse(form["limit"] as string, 25);
                 int start = UMC.Data.Utility.IntParse(form["start"] as string, 0);


                 string sort = form[("sort")] as string;
                 string dir = form[("dir")] as string;

                 var search = new ProjectMember { project_id = project.Id };

                 var Keyword = (form["Keyword"] as string ?? String.Empty);


                 if (String.IsNullOrEmpty(Keyword))
                 {
                     if (String.IsNullOrEmpty(sort) == false)
                     {
                         switch (sort)
                         {
                             case "Admin":
                                 search.AuthType = WebAuthType.Admin;
                                 break;
                             case "Write":
                                 search.AuthType = WebAuthType.User;
                                 break;
                             case "Read":
                                 search.AuthType = WebAuthType.Guest;
                                 break;
                             default:
                                 break;
                         }
                     }
                 }
                 else
                 {
                     search.Alias = Keyword;
                 }
                 int nextIndex;
                 var subs = DataFactory.Instance().Search(search, start, out nextIndex, limit);
                 var ui2 = UISection.Create();
                 var args = new WebMeta().Put("Project", project.Id);
                 var now = Utility.TimeSpan();

                 foreach (var vd in subs)
                 {

                     switch (vd.AuthType)
                     {
                         case WebAuthType.Admin:
                             {
                                 var cellUI = new UIIconNameDesc(new UIIconNameDesc.Item(webr.ImageResolve(request.Url, vd.user_id.Value, "1", "4"), vd.Alias,
                                         $"在{Utility.GetDate(vd.CreationTime)} 加入")
                                         .Click(new UIClick(request.Model, "Account", vd.user_id.ToString())));
                                 if (IsMaster)
                                 {

                                     cellUI.Button("项目主", new UIClick(request.Model, request.Command, new WebMeta(args).Put(g, vd.user_id)), 0x36a3f7);

                                 }
                                 else
                                 {
                                     cellUI.Button("项目主");
                                 }
                                 ui2.Add(cellUI);
                             }
                             break;
                         case WebAuthType.User:

                             {
                                 if ((project.ExpireTime ?? 0) == 0)
                                 {
                                     if (vd.ExpireTime > 0 && vd.ExpireTime < now)
                                     {
                                         DataFactory.Instance().Put(new ProjectMember { AuthType = WebAuthType.Guest, project_id = vd.project_id, user_id = vd.user_id });
                                         goto default;
                                     }
                                 }
                                 var cellUI = new UIIconNameDesc(new UIIconNameDesc.Item(webr.ImageResolve(request.Url, vd.user_id.Value, "1", "4"), vd.Alias,
                                     $"在{Utility.GetDate(vd.CreationTime)} 加入")
                                     .Click(new UIClick(request.Model, "Account", vd.user_id.ToString())));
                                 if (IsMaster)
                                 {
                                     cellUI.Button("作家", new UIClick(request.Model, request.Command, new WebMeta(args).Put(g, vd.user_id)), 0x36a3f7);

                                 }
                                 else
                                 {
                                     cellUI.Button("作家");
                                 }
                                 ui2.Add(cellUI);
                             }
                             break;
                         default:
                             {
                                 var cellUI = new UIIconNameDesc(new UIIconNameDesc.Item(webr.ImageResolve(request.Url, vd.user_id.Value, "1", "4"), vd.Alias,
                                         $"在{Utility.GetDate(vd.CreationTime)} 关注")
                                         .Click(new UIClick(request.Model, "Account", vd.user_id.ToString())));
                                 if (IsMaster)
                                 {
                                     cellUI.Button("设置", new UIClick(request.Model, request.Command, new WebMeta(args).Put(g, vd.user_id)), 0x36a3f7);

                                 }
                                 ui2.Add(cellUI);
                             }
                             break;
                     }

                 }
                 ui2.StartIndex = nextIndex;
                 ui2.IsNext = nextIndex > 0;
                 if (start == 0 && ui2.Length == 0)
                 {
                     var msg = "现在还未有项目成员";
                     switch (sort)
                     {
                         case "Admin":
                             msg = "未有项目主成员";
                             break;
                         case "Write":
                             msg = "未有作家成员";
                             break;
                         case "Read":
                             msg = "未有读者成员";
                             break;
                         default:
                             if (String.IsNullOrEmpty(Keyword) == false)
                             {
                                 msg = String.Format("未搜索到“{0}”对应的项目成员", Keyword);

                             }
                             break;
                     }

                     ui2.Add("Desc", new UMC.Web.WebMeta().Put("desc", msg).Put("icon", "\uF016")
                         , new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"), new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
                 }
                 response.Redirect(ui2);
                 return this.DialogValue("none");
             });
            var UId = Utility.Guid(sId);


            var pm = DataFactory.Instance().ProjectMember(project.Id.Value, UId.Value);
            if (pm == null)
            {
                this.Prompt("此人未关注此项目");
            }
            if (IsMaster == false)
                this.Prompt("只有项目主，才能管理团队成员");
            var arg = request.Arguments;
            var Type = this.AsyncDialog("Type", g =>
            {
                var optls = new Web.UISheetDialog();
                optls.Title = "成员权限";
                if (pm.AuthType != WebAuthType.Admin)
                    optls.Put("设置为项目主", "Admin");

                if (pm.AuthType != WebAuthType.User)
                    optls.Put("设置为作家", "Write");

                if (pm.AuthType != WebAuthType.Guest)
                    optls.Put("设置为读者", "Read");



                return optls;
            });
            //if()
            if (pm.AuthType == WebAuthType.Admin)
            {
                if (DataFactory.Instance().ProjectMember(project.Id.Value, WebAuthType.Admin).Length == 1)
                {
                    this.Prompt("一个项目最少需要一位项目主");
                }
            }

            switch (Type)
            {
                case "Admin":
                    if ((project.ExpireTime ?? 0) == 0 && request.IsMaster == false)
                    {
                        this.Prompt("此为个人项目，不能改变项目主");
                    }
                    DataFactory.Instance().Put(new ProjectMember { user_id = UId, project_id = project.Id.Value, AuthType = WebAuthType.Admin });
                    DataFactory.Instance().Put(new ProjectDynamic
                    {
                        Time = Utility.TimeSpan(),//DateTime.Now,
                        user_id = pm.user_id,
                        Explain = $"被{user.Alias}设置为项目主",
                        project_id = project.Id,
                        refer_id = Utility.UInt64Parse(user.Id.Value),
                        Title = "项目成员",
                        Alias = pm.Alias,
                        Type = DynamicType.Member
                    });
                    break;
                case "Write":
                    if ((project.ExpireTime ?? 0) == 0 && request.IsMaster == false)
                    {
                        response.Redirect(request.Model, "Payment", new WebMeta("Type", "Writer", "Code", $"{Utility.Guid(UId.Value)}-{project.Id.Value}"), true);

                    }
                    else
                    {

                        DataFactory.Instance().Put(new ProjectMember { user_id = UId, project_id = project.Id.Value, AuthType = WebAuthType.User });

                        DataFactory.Instance().Put(new ProjectDynamic
                        {
                            Time = Utility.TimeSpan(DateTime.Now),
                            user_id = pm.user_id,
                            Explain = $"被{user.Alias}设置为作家",
                            project_id = project.Id,
                            refer_id = Utility.UInt64Parse(user.Id.Value),
                            Alias = pm.Alias,
                            Title = "项目成员",
                            Type = DynamicType.Member
                        });
                    }
                    break;
                case "Read":
                    DataFactory.Instance().Put(new ProjectMember { user_id = UId, project_id = project.Id.Value, AuthType = WebAuthType.Guest });

                    DataFactory.Instance().Put(new ProjectDynamic
                    {
                        Time = Utility.TimeSpan(DateTime.Now),
                        user_id = pm.user_id,
                        Explain = $"被{user.Alias}设置为读者",
                        project_id = project.Id,
                        refer_id = Utility.UInt64Parse(user.Id.Value),
                        Title = "项目成员",
                        Alias = pm.Alias,
                        Type = DynamicType.Member
                    });
                    break;
            }
            this.Context.Send("Subject.Team", true);






        }

    }
}